﻿using System.Threading.Tasks;
using Xamarin.Essentials;

namespace RaceHFTools.Utils
{
    public class Permission
    {
        public static async Task<bool> CheckAndroidPermission()
        {
            if (await CheckStorageReadPermission() != PermissionStatus.Granted)
                return false;
            if (await CheckStorageWritePermission() != PermissionStatus.Granted)
                return false;
            if (await CheckLocationPermission() != PermissionStatus.Granted)
                return false;

            return true;
        }

        public static async Task RequestAndroidPermission()
        {
            await RequestStorageReadPermission();
            await RequestStorageWritePermission();
            await RequestLocationPermission();
        }

        static async Task<PermissionStatus> CheckStorageReadPermission()
        {
            return await Permissions.CheckStatusAsync<Permissions.StorageRead>();
        }

        static async Task<PermissionStatus> RequestStorageReadPermission()
        {
            PermissionStatus status = await CheckStorageReadPermission();

            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
            }

            return status;
        }

        static async Task<PermissionStatus> CheckStorageWritePermission()
        {
            return await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
        }

        static async Task<PermissionStatus> RequestStorageWritePermission()
        {
            PermissionStatus status = await CheckStorageWritePermission();

            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.StorageWrite>();
            }

            return status;
        }

        static async Task<PermissionStatus> CheckLocationPermission()
        {
            return await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
        }

        static async Task<PermissionStatus> RequestLocationPermission()
        {
            PermissionStatus status = await CheckLocationPermission();

            if (status != PermissionStatus.Granted)
            {
                status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
            }

            return status;
        }

    }
}
